package com.example.baijiebrower.update;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @ClassName CheckUpdateService
 * @Author liufeng
 * @Date 2024/9/14
 * @email liufeng@szbaijie.cn
 * @Description
 */
public class CheckUpdateService extends Service {

    private static final String TAG = "CheckUpdateService";
    private ExecutorService mExecutorService;
    private UpdateJson updateJson;
    private int versionCode;
    private String versionName;
    private Context mContext;

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand: ");
        mContext = this;
        mExecutorService = Executors.newFixedThreadPool(1);
        mExecutorService.execute(checkUpdateThread);
        return START_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private String getVersionName() {
        try {
            PackageManager pm = getPackageManager();
            return pm.getPackageInfo(getPackageName(), 0).versionName;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    private int getVersionCode() {
        try {
            PackageManager pm = getPackageManager();
            return pm.getPackageInfo(getPackageName(), 0).versionCode;
        }catch (Exception e){
            e.printStackTrace();
        }
        return 0;
    }

    private Thread checkUpdateThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                updateJson = new UpdateJson();
                updateJson.jsonToNetwork();
                versionName = getVersionName();
                versionCode = getVersionCode();
                if (updateJson.compareVersionsName(updateJson.getVersionName(), versionName) && updateJson.getVersionCode() > versionCode){
                    Intent localIntent = new Intent("com.example.baijiebrower.ACTION_SHOW_UPDATE_DIALOG");
                    localIntent.putExtra("url", updateJson.getDownloadUrl());
                    localIntent.putExtra("versionName", updateJson.getVersionName());
                    localIntent.putExtra("updateMessage", updateJson.getUpdateMessage());
                    LocalBroadcastManager.getInstance(mContext).sendBroadcast(localIntent);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    });
}
